package test.functionQuery.hhpositionsort;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;

import com.hunteron.common4s.jdk.string.str.StringTools;

public class PositionSortValueSource extends ValueSource {

    // 保存默认排序值
    private ValueSource valueSource = null;

    private ValueSource defaultSortValueSource = null;

    private Map<Long, Integer> sortMap = new HashMap<>(0);

    public PositionSortValueSource(ValueSource valueSource, ValueSource defaultSortValueSource, Map<Long, Integer> sortMap) {
        super();
        this.valueSource = valueSource;
        this.defaultSortValueSource = defaultSortValueSource;
        this.sortMap = sortMap;
    }

    @Override
    public FunctionValues getValues(@SuppressWarnings("rawtypes") Map context, AtomicReaderContext readerContext) throws IOException {
        final FunctionValues positionIdValue = valueSource.getValues(context, readerContext);

        final FunctionValues defaultSortFunctionValues = defaultSortValueSource.getValues(context, readerContext);

        return new FloatDocValues(this) {
            @Override
            public float floatVal(int doc) {
                Long positionId = StringTools.getLong(positionIdValue.strVal(doc), -1L);
                if (positionId < 0) {
                    return 0F;
                }
                float value = 0;
                // 人职匹配度
                Integer rank = sortMap.get(positionId);
                if (rank != null) {
                    value += rank * 10000000000l;

                }
                // 计算排序值
                long defaultSortValue = StringTools.getLong(defaultSortFunctionValues.strVal(doc), -1);

                value += defaultSortValue;

                return value;
            }

            @Override
            public String toString(int doc) {
                return description();
            }
        };
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public String description() {
        return "positionDefaultSort";
    }

    public static void main(String[] args) {
        System.out.println(Float.MAX_VALUE);
    }
}
